'use strict';
/**
 * @fileoverview 竞技场
 * @author sundbcn@gmail.com (sun debing)
 */

var _ = require('lodash');
var moment = require('moment');
var mongoose = require('mongoose');
var dataApi = require('../libs/dataApi');
var configUtil = require('../util/configUtil');
var constantUtil = require('../util/constantUtil');
var mgrUtil = require('../util/mgrUtil');
var arenaShopItemSchema = require('./arena/arenaShopItemSchema.js');
var eventType = require('../consts/eventType.js');
var arenaConf = require('../config/arenaConf.js');

/**
 * 初始化挑战次数
 * @return {[type]} [description]
 */
var _initFightTimes = function () {
    return constantUtil.value('arena_challenge_times');
};

/**
 * 竞技场
 */
var arenaSchema = new mongoose.Schema({
    // 角色id
    role_id: {
        type: Number,
        required: true,
        unique: true,
        index: true
    },

    // NPCID，玩家的为0
    npc_id: {
        type: Number,
        required: true,
        default: 0
    },

    // 排名
    rank: {
        type: Number,
        default: 0
    },

    // 最高排名
    max_rank: {
        type: Number,
        default: 999999
    },

    // 剩余挑战次数
    remain_fight_times: {
        type: Number,
        default: _initFightTimes
    },

    // 购买挑战次数的次数
    buy_fight_times: {
        type: Number,
        default: 0
    },

    // 被哪个玩家锁定
    locked_role_id: {
        type: Number,
        default: 0
    },

    // 锁定时间
    locked_time: {
        type: Number,
        default: 0
    },

    // 竞技场商城物品
    arena_shop: {
        type: [arenaShopItemSchema],
        default: []
    },

    // 刷新商城次数
    refresh_shop_times: {
        type: Number,
        default: 0
    },

    // 进攻阵容
    att_soldier_list: {
        type: [Number],
        default: []
    },

    // 防守阵容
    def_soldier_list: {
        type: [Number],
        default: []
    },

    // 竞技场币
    arena_coin: {
        type: Number,
        default: 0
    },

    // 进攻战力
    att_power: {
        type: Number,
        default: 0
    },

    // 防守战力
    def_power: {
        type: Number,
        default: 0
    },

    // 战斗CD
    next_fight_tm: {
        type: Number,
        default: 0
    },
});

arenaSchema.pre('save', function (next) {
    this.increment();
    if (!this.isNew && !!this.isModified()) {
        this.pushModify();
    }
    next();
});

/**
 * 获取修改
 * @return {[type]} [description]
 */
arenaSchema.methods.getLastChange = function () {
    var change_info = this.toJSON();
    change_info.open_game_time = configUtil.getOpenGameTime();
    change_info.open_game_date = configUtil.getOpenGameDate();
    return change_info;
};

/**
 * 推送给用户
 * @return {[type]} [description]
 */
arenaSchema.methods.push = function () {
    this.pushModify();
};

arenaSchema.methods.pushModify = function () {
    var self = this;
    mgrUtil.sendStatusMessage(
        [self.role_id],
        eventType.ON_ARENA_CHANGE,
        self.getLastChange(),
        function (err, fails) {
            if (err) {
                console.error('send arena message error: %j, fail ids: %j', err, fails);
                return;
            }
        }
    );
};

if (!arenaSchema.options.toJSON) {
    arenaSchema.options.toJSON = {};
}
/* jshint unused:false */
arenaSchema.options.toJSON.transform = function (doc, ret) {
    delete ret._id;
    delete ret.__v;
};

/**
 * 设置竞技场攻/防阵容
 */
arenaSchema.methods.setSoldierList = function (opt_type, soldier_list) {
    var dst_soldier_list = (opt_type === 1) ? this.att_soldier_list : this.def_soldier_list;
    dst_soldier_list.splice(0, dst_soldier_list.length);
    _.forEach(soldier_list, function (soldier_type) {
        dst_soldier_list.push(soldier_type);
    });
};

/**
 * 减少竞技场商城物品可购买次数
 */
arenaSchema.methods.decShopItemCount = function (shop_pos) {
    var self = this;
    var success = false;
    _.forEach(self.arena_shop, function (shop_item) {
        if (shop_item.shop_pos === shop_pos) {
            if (shop_item.count > 0) {
                shop_item.count--;
                success = true;
            }
            return false;
        }
        return true;
    });
    return success;
};

/**
 * 减少可挑战次数
 */
arenaSchema.methods.decFightTimes = function () {
    if (this.remain_fight_times < 1) {
        return false;
    }
    this.remain_fight_times--;
    return true;
};

/**
 * 取出指店位置商城物品信息
 */
arenaSchema.methods.getShopItem = function (shop_pos) {
    var self = this;
    return _.find(self.arena_shop, {
        shop_pos: shop_pos
    });
};

/**
 * 增加竞技币
 */
arenaSchema.methods.addArenaCoin = function (add_coin) {
    add_coin = +add_coin;
    this.arena_coin += add_coin;
};

/**
 * 消耗竞技币
 */
arenaSchema.methods.useArenaCoin = function (arena_coin) {
    var self = this;
    arena_coin = +arena_coin;
    if (self.arena_coin < arena_coin) {
        return false;
    }
    self.arena_coin -= arena_coin;
    return true;
};

/**
 * 手动刷新商城
 */
arenaSchema.methods.manulRefreshShop = function () {
    var self = this;

    var arena_shop_refresh_times_limit = constantUtil.value('arena_shop_refresh_times_limit');
    if (self.refresh_shop_times >= arena_shop_refresh_times_limit) {
        return false;
    }

    self.refresh_shop_times++;
    self.refreshShop();
    return true;
};

/**
 * 商城刷新
 */
arenaSchema.methods.refreshShop = function () {
    var self = this;

    // 执行刷新
    self.arena_shop = [];
    var arena_shop = self.arena_shop;

    // 必出
    var must_appear_list = arenaConf.getMustAppearList();
    _.forEach(must_appear_list, function (item) {
        arena_shop.push({
            shop_pos: item.shop_pos,
            shop_id: item.shop_id,
            count: item.count
        });
    });

    // 随机
    var arena_shop_goods_num = constantUtil.value('arena_shop_goods_num');
    var total_prob = arenaConf.getTotalProb();
    var shop_rate_info = arenaConf.getShopRateInfo();
    for (var shop_pos = must_appear_list.length + 1; shop_pos <= arena_shop_goods_num; shop_pos++) {
        var rand_val = _.random(0, total_prob - 1);
        var shop_item = _findShopItemByRateVal(rand_val, shop_rate_info);
        if (!!shop_item) {
            arena_shop.push({
                shop_pos: shop_pos,
                shop_id: shop_item.shop_id,
                count: shop_item.count
            });
        }
    }
    return true;
};

/**
 * 按随机概率值，查找商城ID
 */
var _findShopItemByRateVal = function (rate_val, shop_rate_info) {
    var shop_item = _.find(shop_rate_info, function (rate_item) {
        return rate_item.sum_rate > rate_val;
    });
    return shop_item;
};

mongoose.model('Arena', arenaSchema);
